package com.itheima.behaviour.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.behaviour.dto.LikesBehaviourDto;
import com.itheima.behaviour.dto.UpdateArticleMess;
import com.itheima.behaviour.mapper.ApBehaviorEntryMapper;
import com.itheima.behaviour.mapper.ApLikesBehaviorMapper;
import com.itheima.behaviour.pojo.ApBehaviorEntry;
import com.itheima.behaviour.pojo.ApLikesBehavior;
import com.itheima.behaviour.service.ApLikesBehaviorService;
import com.itheima.common.constants.BusinessConstants;
import com.itheima.common.constants.SystemConstants;
import com.itheima.common.enums.HttpCodeEnum;
import com.itheima.common.exception.LeadNewsException;
import com.itheima.common.util.RequestContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @version 1.0
 * @description <p>APP点赞行为 业务实现</p>
 * @package com.itheima.behaviour.service.impl
 */
@Service
public class ApLikesBehaviorServiceImpl extends ServiceImpl<ApLikesBehaviorMapper, ApLikesBehavior> implements ApLikesBehaviorService {

    @Autowired
    private ApBehaviorEntryMapper apBehaviorEntryMapper;

    @Autowired
    private KafkaTemplate kafkaTemplate;

    /**
     * app点赞与取消
     *
     * @param dto
     */
    @Override
    public void likeBehavior(LikesBehaviourDto dto) {
        //参数校验
        if (dto == null || dto.getArticleId() == null
                || dto.getType() > 2 || dto.getType() < 0 || dto.getOperation() > 1) {
            throw new LeadNewsException(HttpCodeEnum.PARAM_INVALID);
        }
        //2. 判断操作实体是匿名还是登录用户
        long loginUserId = Long.parseLong(RequestContextUtil.getUserId());
        // 假设实体为当前登录用户id
        Long entryId = loginUserId;
        // 假设实体类型为用户
        int type = SystemConstants.TYPE_USER;
        if(SystemConstants.ANONYMOUS_USER_ID == loginUserId){
            //如果是匿名，则实体类型为备
            type = SystemConstants.TYPE_E;
            //那么相应的，实体Id就为设备的id
            entryId = dto.getEquipmentId();
        }
        ApBehaviorEntry entry = apBehaviorEntryMapper.findByEntryIdAndType(entryId, type);
        if(null != entry) {
            //判断记录是否存在，如果存在
            LambdaQueryWrapper<ApLikesBehavior> lqw = new LambdaQueryWrapper<>();
            lqw.eq(ApLikesBehavior::getArticleId, dto.getArticleId())
                    .eq(ApLikesBehavior::getEntryId, entry.getId())
                    .eq(ApLikesBehavior::getType,dto.getType());//类型为文章
            ApLikesBehavior likesBehavior = getOne(lqw);
            if(null == likesBehavior){
                // 不存在则添加
                ApLikesBehavior pojo = new ApLikesBehavior();
                pojo.setArticleId(dto.getArticleId());
                pojo.setEntryId(entry.getId());
                pojo.setType(dto.getType());//文章
                pojo.setOperation(dto.getOperation());
                pojo.setCreatedTime(LocalDateTime.now());
                save(pojo);
            }else{
                //获取已存在的操作类型
                Integer dbOperation = likesBehavior.getOperation();
                if(dbOperation.intValue() != dto.getOperation().intValue()){
                    //如果操作类型不同，则更新
                    ApLikesBehavior updatePojo = new ApLikesBehavior();
                    updatePojo.setOperation(dto.getOperation());
                    updatePojo.setId(likesBehavior.getId());
                    updateById(updatePojo);
                }
            }
            UpdateArticleMess mess = new UpdateArticleMess();
            mess.setArticleId(dto.getArticleId());
            mess.setType(UpdateArticleMess.UpdateArticleType.LIKES);
            if(dto.getOperation() == 1){
                mess.setNum(1);
            }else{
                mess.setNum(-1);
            }
            kafkaTemplate.send(BusinessConstants.MqConstants.HOT_ARTICLE_SCORE_TOPIC, JSON.toJSONString(mess));
        }
    }
}
